package cn.tedu.micro.demo.rabbit.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

/**
 * 在控制层 注入现成的对象RabbitTemplate
 * 调用其API方法将消息封装 发送到目的地(交换机)
 */
@RestController
@Slf4j
public class SendController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * GET 请求
     * /send
     * String msg 发送的消息
     * "ok"
     */
    @GetMapping("/send")
    public String send(String msg){
        //channel.basicPublish("交换机","路由key",properties,body)
        //方案1 我们需要自定义 数据的序列化(boyd) 自定义属性和headers
        //1.1 消息体
        byte[] body=msg.getBytes(StandardCharsets.UTF_8);
        //1.2 消息属性 可以在消息属性里 添加字符集 影响消费反序列化使用
        //MessageProperties props=new MessageProperties();
        //props.setContentEncoding("UTF-8");
        //Message message=new Message(body,props);
        //1.3 调用生产发送 convertAndSend send
        //rabbitTemplate.send("direct-demo-ex","demo-rk",message);//消息必须是Message类型
        //rabbitTemplate.convertAndSend("direct-demo-ex","demo-rk",message);//消息可以是object
        //方案2 如果直接将object类型发送,底层代码会自动做序列化和message属性封装
        rabbitTemplate.convertAndSend("direct-demo-ex","demo-rk",msg);
        return "ok";
    }
}
